package com.newasia.management.services;/**
 * Created by mic on 2019/7/30.
 */


import com.newasia.commons.tool.exception.ValidateException;
import com.newasia.management.IHomepageNavService;
import com.newasia.management.constants.ManagementRetCode;
import com.newasia.management.converter.HomePageNavConverter;
import com.newasia.management.dal.homepage.entitys.PanelNav;
import com.newasia.management.dal.homepage.entitys.PanelNavExample;
import com.newasia.management.dal.homepage.entitys.PanelNavUrl;
import com.newasia.management.dal.homepage.entitys.PanelNavUrlExample;
import com.newasia.management.dal.homepage.persistence.PanelNavMapper;

import com.newasia.management.dal.homepage.persistence.PanelNavUrlMapper;
import com.newasia.management.dal.item.entitys.ItemCat;
import com.newasia.management.dal.item.entitys.ItemCatExample;
import com.newasia.management.dal.item.entitys.ItemSku;
import com.newasia.management.dal.item.entitys.ItemSpu;
import com.newasia.management.dal.item.persistence.ItemCatMapper;
import com.newasia.management.dal.item.persistence.ItemSkuMapper;
import com.newasia.management.dal.item.persistence.ItemSpuMapper;
import com.newasia.management.dal.user.entitys.SysMenu;
import com.newasia.management.dal.user.entitys.SysMenuExample;
import com.newasia.management.dal.user.persistence.SysMenuMapper;
import com.newasia.management.dto.HomepageNav.*;
import com.newasia.management.dto.HomepageNavItem.*;
import com.newasia.management.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class HomepageNavImpl implements IHomepageNavService {

    @Autowired
    PanelNavMapper panelNavMapper;

    @Autowired
    PanelNavUrlMapper panelNavUrlMapper;

    @Autowired
    HomePageNavConverter homePageNavConverter;

    @Autowired
    ItemCatMapper itemCatMapper;


    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    SysMenuMapper sysMenuMapper;

    @Autowired
    ItemSpuMapper itemSpuMapper;

    /**
     * 添加主页菜单
     * @return
     */
    @Override
    public CreateNavResponse createNav(CreateNavRequest request) {
        CreateNavResponse response = new CreateNavResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            request.requestCheck();
            clearHomepageNavCache();
            int i = request.getType().intValue();
            Date date = new Date();
            PanelNav data =new PanelNav();
            if(i==0){
                ItemCat itemCat = itemCatMapper.selectByPrimaryKey(request.getCatId());
                if(itemCat.getParentId()!=0){


                    throw new ValidateException(
                            ManagementRetCode.CHOOSE_FIRST.getCode(),
                            ManagementRetCode.CHOOSE_FIRST.getMessage());
                }
                data.setNavName(itemCat.getCatName());
            }else{
                data.setNavName(request.getNavName()==null?"未设置标题":request.getNavName());
            }


            data.setCreated(date);
            data.setUpdated(date);
            data.setCatId(request.getCatId());
            data.setSortOrder(request.getSortOrder()==null?0:request.getSortOrder());
            data.setType(request.getType());


            panelNavMapper.insert(data);
        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }


    /**
     * 添加主页菜单子项
     * @return
     */
    @Override
    public CreateNavItemResponse createNavItem(CreateNavItemRequest request) {
        CreateNavItemResponse response = new CreateNavItemResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            request.requestCheck();
            clearHomepageNavCache();
            PanelNav panelNav = panelNavMapper.selectByPrimaryKey(request.getNavId());
            if(panelNav==null){
                throw new ValidateException(
                        ManagementRetCode.NOT_EXIST.getCode(),
                        ManagementRetCode.NOT_EXIST.getMessage());
            }
            Date date=new Date();

            PanelNavUrl data=new PanelNavUrl();



            int i = panelNav.getType().intValue();

            if(i==0){
                throw new ValidateException(
                        ManagementRetCode.REQUISITE_PARAMETER_ERROR.getCode(),
                        ManagementRetCode.REQUISITE_PARAMETER_ERROR.getMessage());
            }else if(i==1){
                if(request.getUrlName()!=null&&request.getFullUrl()!=null&&!"".equals(request.getUrlName())&&!"".equals(request.getFullUrl())){
                    data.setUrlName(request.getUrlName());
                    data.setFullUrl(request.getFullUrl());
                }else{
                    throw new ValidateException(
                    ManagementRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode(),
                            ManagementRetCode.REQUISITE_PARAMETER_NOT_EXIST.getMessage());
                }

            }else if(i==2){
                log.warn(request.getSpuId()+"---------------");
               if(request.getSpuId()!=null&&!"".equals(request.getSpuId())){
                   ItemSpu itemSpu = itemSpuMapper.selectByPrimaryKey(request.getSpuId());
                   if(itemSpu.getStatus()==1){
                       data.setItemId(request.getSpuId());
                   }else{
                       throw new ValidateException(
                               ManagementRetCode.NOT_UP.getCode(),
                               ManagementRetCode.NOT_UP.getMessage());
                   }
               }else{
                   throw new ValidateException(
                           ManagementRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode(),
                           ManagementRetCode.REQUISITE_PARAMETER_NOT_EXIST.getMessage());
               }

            }

            data.setCreated(date);
            data.setUpdated(date);
            data.setNavId(request.getNavId());
            data.setSortOrder(request.getSortOrder()==null?0:request.getSortOrder());
            panelNavUrlMapper.insert(data);

        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            return response;
        }
        return response;
    }



    /**
     * 删除主页菜单
     * @return
     */
    @Override
    public DeleteNavResponse deleteNav(Long navId) {
        DeleteNavResponse response = new DeleteNavResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{

            clearHomepageNavCache();
            PanelNav panelNav = panelNavMapper.selectByPrimaryKey(navId);
            if(panelNav!=null){
                PanelNavUrlExample ee=new PanelNavUrlExample();
                ee.createCriteria().andNavIdEqualTo(navId);
                long l = panelNavUrlMapper.countByExample(ee);
                if(l>0){
                    throw new ValidateException(
                            ManagementRetCode.EXIST_ITEM_NAV.getCode(),
                            ManagementRetCode.EXIST_ITEM_NAV .getMessage()
                    );
                }

                panelNavMapper.deleteByPrimaryKey(navId);
            }else{
                throw new ValidateException(
                        ManagementRetCode.NOT_EXIST.getCode(),
                        ManagementRetCode.NOT_EXIST .getMessage()
                );
            }
        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }


    /**
     * 删除主页菜单子项
     * @return
     */
    @Override
    public DeleteNavItemResponse deleteNavItem(Long navItemId) {
        DeleteNavItemResponse response = new DeleteNavItemResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            clearHomepageNavCache();
            panelNavUrlMapper.deleteByPrimaryKey(navItemId);
        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }



    /**
     * 修改主页菜单
     * @return
     */
    @Override
    public ChangeNavResponse changeNav(Long navId, ChangeNavRequest request) {
        ChangeNavResponse response = new ChangeNavResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            request.requestCheck();
            clearHomepageNavCache();
            PanelNav nav=new PanelNav();

            Integer type = request.getType();


                PanelNav panelNav = panelNavMapper.selectByPrimaryKey(navId);
                Integer type1 = panelNav.getType();

                if (type1.intValue()!=type.intValue()){
                    PanelNavUrlExample ee=new PanelNavUrlExample();
                    ee.createCriteria().andNavIdEqualTo(navId);
                    long l = panelNavUrlMapper.countByExample(ee);
                    if(l>0){
                        throw new ValidateException(
                                ManagementRetCode.EXIST_ITEM_NAV.getCode(),
                                ManagementRetCode.EXIST_ITEM_NAV .getMessage()
                        );
                    }

                    if(type==0){
                        ItemCat itemCat = itemCatMapper.selectByPrimaryKey(request.getCatId());
                        if(itemCat.getParentId()!=0){

                            throw new ValidateException(
                                    ManagementRetCode.CHOOSE_FIRST.getCode(),
                                    ManagementRetCode.CHOOSE_FIRST.getMessage());
                        }
                        nav.setNavName(itemCat.getCatName());
                    }
                }


            Date date = new Date();
                if(type.intValue()==0&&request.getCatId()!=null){
                     nav.setCatId(request.getCatId());
                }
            nav.setId(navId);
            nav.setType(type);
            nav.setSortOrder(request.getSortOrder());
            nav.setUpdated(date);
            nav.setNavName(request.getNavName());


            panelNavMapper.updateByPrimaryKeySelective(nav);
        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }

    /**
     * 修改主页菜单子项
     * @return
     */
    @Override
    public ChangeNavItemResponse changeNavItem(Long navItemId, ChangeNavItemRequest request) {
        ChangeNavItemResponse response = new ChangeNavItemResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            request.requestCheck();
            clearHomepageNavCache();
            PanelNavUrl panelNavUrl = panelNavUrlMapper.selectByPrimaryKey(navItemId);

            PanelNav panelNav = panelNavMapper.selectByPrimaryKey(panelNavUrl.getNavId());
            if(panelNav==null){
                throw new ValidateException(
                        ManagementRetCode.NOT_EXIST.getCode(),
                        ManagementRetCode.NOT_EXIST.getMessage());
            }
            Date date=new Date();

            PanelNavUrl data=new PanelNavUrl();

            int i = panelNav.getType().intValue();


            if(i==0){
                throw new ValidateException(
                        ManagementRetCode.REQUISITE_PARAMETER_ERROR.getCode(),
                        ManagementRetCode.REQUISITE_PARAMETER_ERROR.getMessage());
            }else if(i==1){
                    data.setUrlName(request.getUrlName());
                    data.setFullUrl(request.getFullUrl());
            }else if(i==2){

                if(panelNavUrl.getItemId().longValue()!=request.getSpuId().longValue()&&request.getSpuId()!=null){
                    ItemSpu itemSpu = itemSpuMapper.selectByPrimaryKey(request.getSpuId());
                    if(itemSpu.getStatus()==1){
                        data.setItemId(request.getSpuId());
                    }else{
                        throw new ValidateException(
                                ManagementRetCode.NOT_UP.getCode(),
                                ManagementRetCode.NOT_UP.getMessage());
                    }

                }

            }



            data.setId(navItemId);
            data.setUrlName(request.getUrlName());
            data.setSortOrder(request.getSortOrder());
            data.setFullUrl(request.getFullUrl());
            data.setUpdated(date);
            data.setItemId(request.getSpuId());


            panelNavUrlMapper.updateByPrimaryKeySelective(data);

        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;

    }


        /**
          * 获取主页菜单
          * @return
          */
    @Override
    public GetNavResponse getNavList() {
        GetNavResponse response = new GetNavResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            PanelNavExample panelNavExample = new PanelNavExample();
            panelNavExample.setOrderByClause("sort_order asc");
            List<PanelNav> panelNavs = panelNavMapper.selectByExample(panelNavExample);
            List<NavDto> navDtos = homePageNavConverter.item2dto(panelNavs);
            for (NavDto dto:navDtos) {
                if(dto.getType()==0){
                    ItemCat itemCat = itemCatMapper.selectByPrimaryKey(dto.getCatId());
                    dto.setNavName(itemCat.getCatName());
                }else if(dto.getType()==1){
                    PanelNavUrlExample example=new PanelNavUrlExample();
                    example.createCriteria().andNavIdEqualTo(dto.getId());
                    example.setOrderByClause("sort_order asc");
                    List<PanelNavUrl> panelNavUrls = panelNavUrlMapper.selectByExample(example);
                    dto.setChildren(homePageNavConverter.navitem2dto(panelNavUrls));
                }else if(dto.getType()==2){
                    PanelNavUrlExample example=new PanelNavUrlExample();
                    example.createCriteria().andNavIdEqualTo(dto.getId());
                    example.setOrderByClause("sort_order asc");
                    List<PanelNavUrl> panelNavUrls = panelNavUrlMapper.selectByExample(example);
                    List<NavItemDto> data=new ArrayList<>();
                    for (PanelNavUrl url:panelNavUrls) {
                        NavItemDto navDto =new  NavItemDto();
                        Long spuId = url.getItemId();
                        ItemSpu itemSpu = itemSpuMapper.selectByPrimaryKey(spuId);
                        if (itemSpu!=null){
                            navDto.setCover(itemSpu.getImage());
                            navDto.setSpuName(itemSpu.getTitle());
                        }
                        navDto.setId(url.getId());
                        navDto.setNavId(url.getNavId());
                        navDto.setSortOrder(url.getSortOrder());
                        navDto.setCreated(url.getCreated());
                        navDto.setUpdated(url.getUpdated());
                        data.add(navDto);
                    }
                    dto.setChildren(data);
                }
            }
            response.setData(navDtos);
        }catch (Exception e){
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
            return response;
        }
        return response;
    }


    private void clearHomepageNavCache(){
        SysMenuExample ex=new SysMenuExample();
        ex.createCriteria().andStatusEqualTo(0);
        List<SysMenu> sysMenus = sysMenuMapper.selectByExample(ex);
        List<String> data=new ArrayList<>();
        for (SysMenu s:sysMenus) {
            data.add(s.getMenuId().longValue()+"");
        }
        data.add("null");
        data.add("0");

        for (String s:data) {
            StringBuilder home_page_nav=new StringBuilder("home_page_nav");
            home_page_nav.append(":").append(s);
            RBucket bucket = redissonClient.getBucket(home_page_nav.toString());
            bucket.expire(0, TimeUnit.DAYS);
        }

        RBucket product_cate=redissonClient.getBucket("product_cate");
        product_cate.expire(0, TimeUnit.DAYS);
    }
}
